package com.fhz.kotlinmvvm.service

import android.app.IntentService
import android.content.Intent
import android.graphics.BitmapFactory
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL


/**
 *
 */
class MyIntentService : IntentService("MyIntentService") {


    /**
     * 方法结束,服务自动停止
     */
    override fun onHandleIntent(intent: Intent?) {
        var url:URL? = null
        var openConnection:HttpURLConnection? = null
        var inputStream:InputStream? = null
        try {
            url  = URL("https://alifei05.cfp.cn/creative/vcg/veer/800/new/VCG41N883173568.jpg")
            openConnection = url.openConnection() as HttpURLConnection
//        openConnection.readTimeout = 10
            openConnection.connect()
            //http的状态码有多少种
            /**
             * 100
             * 200 相应成功
             * 302 重定向
             * 404 资源不存在
             * 500 服务内部错误
             *
             */
            if(openConnection.responseCode == 200){
                inputStream = openConnection.inputStream
                val bitmap = BitmapFactory.decodeStream(inputStream)
                //把binmap 存入到sd卡
                println("下载成功!")
            }
        }catch (e:Exception){

        }finally {
            if(openConnection != null){
                openConnection.disconnect()
            }
            if(inputStream != null){
                inputStream.close()
            }

        }

    }


}